import csv
import json
import re
def clean_value(value):
    """数据清洗函数"""
    cleaned = re.sub(r'[@~°]', '', value)
    cleaned = re.sub(r'[^\d.-]', '', cleaned)
    return cleaned
def csv_to_json(csv_path, json_path):
    with open(csv_path, 'r', encoding='utf-8') as f_csv:
        
        clean_lines = []
        for line in f_csv:
            cleaned_line = re.sub(r'[,\n]+', ',', line.strip())
            clean_lines.append(cleaned_line)
        
        reader = csv.DictReader(clean_lines)
        
        json_data = []
        for row in reader:
            processed_row = {
                "city": "",          
                "year_on_year": "",  
                "month_on_month": "",
                "base_year": ""      
            }
            
            for k, v in row.items():
                if "城市" in k:
                    processed_row["city"] = clean_value(v)
                elif "同比" in k:
                    processed_row["year_on_year"] = f"{clean_value(v).strip('%')}%"
                elif "环比" in k:
                    if "环比比" in k:
                        k = "环比"
                    processed_row["month_on_month"] = f"{clean_value(v).strip('%')}%"
                elif "定基" in k:
                    processed_row["base_year"] = f"{clean_value(v).strip('%')}%"

            json_data.append(processed_row)

    with open(json_path, 'w', encoding='utf-8') as f_json:
        json.dump(json_data, f_json, ensure_ascii=False, indent=2)

if __name__ == "__main__":
    try:
        csv_to_json(
            r"D:\qq\price2016.csv",  
            r"D:\qq\price2016.json"   
        )
        print(" 转换成功！JSON文件已生成")
    except Exception as e:
        print(f" 转换失败：{str(e)}")